
<template>
  <div class="user z-h-100">
    <!-- <el-scrollbar ref="elScrollbar" class="scrollbarCls"> -->
    <el-row :span="24" class="z-h-100">

      <el-col v-loading="treeData.length===0" :xs="24" :sm="24" :md="5" class="user__tree z-h-100">
        <el-input
          v-model="filterText"
          placeholder="输入关键字进行过滤"
          size="mini"
          clearable
          style="margin-bottom:10px"
        />
        <div class="treeWrapper">
          <el-scrollbar ref="treeScrollbar" class="scrollbarCls">
            <el-tree
              ref="tree"
              :props="treeOption"
              :data="treeData"
              :filter-node-method="filterNode"
              :default-expanded-keys="defaultExpandedKeys"
              :node-key="treeOption.nodeKey"
              :expand-on-click-node="false"
              @node-click="nodeClick"
              @node-expand="toggleChange"
              @node-collapse="toggleChange"
            />
          </el-scrollbar>
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :md="19" class="user__main z-h-100">
        <el-scrollbar ref="elScrollbar" class="scrollbarCls">
          <avue-crud
            ref="crud"
            v-model="form"
            :option="option"
            :page="page"
            :table-loading="listLoading"
            :before-open="handleOpenBefore"
            :data="list"
            @on-load="getList"
            @search-change="handleFilter"
            @refresh-change="handleRefreshChange"
            @row-update="update"
            @row-save="create"
          >
            <template slot="menuLeft">
              <el-button
                v-if="sys_user_add"
                class="filter-item"
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="handleCreate"
              >添加</el-button>
            </template>
            <template slot="name" slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
            <template slot="username" slot-scope="scope">
              <span>{{ scope.row.username }}</span>
            </template>
            <template slot="role" slot-scope="scope">
              <span v-for="(roles,index) in scope.row.roleList" :key="index">
                <el-tag>{{ roles.roleName }}</el-tag>&nbsp;&nbsp;
              </span>
            </template>
            <template slot="deptId" slot-scope="scope">{{ scope.row.deptName }}</template>
            <template slot="lockFlag" slot-scope="scope">
              <el-tag>{{ scope.label }}</el-tag>
            </template>
            <template slot="menu" slot-scope="scope">
              <el-button
                v-if="sys_user_edit"
                type="text"
                size="mini"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row,scope.index)"
              >编辑</el-button>
              <el-button
                v-if="sys_user_del"
                type="text"
                size="mini"
                icon="el-icon-delete"
                @click="deletes(scope.row,scope.index)"
              >删除</el-button>
            </template>
            <template slot="deptIdForm">
              <avue-input
                v-model="form.deptId"
                :node-click="getNodeData"
                :dic="treeDeptData"
                :props="defaultProps"
                type="tree"
                placeholder="请选择所属部门"
              />
            </template>
            <template slot="roleForm">
              <avue-select
                v-model="role"
                :dic="rolesOptions"
                :props="roleProps"
                multiple
                placeholder="请选择角色"
              />
            </template>
          </avue-crud>
        </el-scrollbar>
      </el-col>
    </el-row>
    <!-- <basic-container>
        <el-row :span="24">
          <el-col :xs="24" :sm="24" :md="5" class="user__tree">
            <avue-tree :option="treeOption" :data="treeData" @node-click="nodeClick" />
          </el-col>
          <el-col :xs="24" :sm="24" :md="19" class="user__main">
            <avue-crud
              ref="crud"
              v-model="form"
              :option="option"
              :page="page"
              :table-loading="listLoading"
              :before-open="handleOpenBefore"
              :data="list"
              @on-load="getList"
              @search-change="handleFilter"
              @refresh-change="handleRefreshChange"
              @row-update="update"
              @row-save="create"
            >
              <template slot="menuLeft">
                <el-button
                  v-if="sys_user_add"
                  class="filter-item"
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="handleCreate"
                >添加</el-button>
              </template>
              <template slot="name" slot-scope="scope">
                <span>{{ scope.row.name }}</span>
              </template>
              <template slot="username" slot-scope="scope">
                <span>{{ scope.row.username }}</span>
              </template>
              <template slot="role" slot-scope="scope">
                <span v-for="(roles,index) in scope.row.roleList" :key="index">
                  <el-tag>{{ roles.roleName }}</el-tag>&nbsp;&nbsp;
                </span>
              </template>
              <template slot="deptId" slot-scope="scope">{{ scope.row.deptName }}</template>
              <template slot="lockFlag" slot-scope="scope">
                <el-tag>{{ scope.label }}</el-tag>
              </template>
              <template slot="menu" slot-scope="scope">
                <el-button
                  v-if="sys_user_edit"
                  type="text"
                  size="mini"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row,scope.index)"
                >编辑</el-button>
                <el-button
                  v-if="sys_user_del"
                  type="text"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deletes(scope.row,scope.index)"
                >删除</el-button>
              </template>
              <template slot="deptIdForm">
                <avue-input
                  v-model="form.deptId"
                  :node-click="getNodeData"
                  :dic="treeDeptData"
                  :props="defaultProps"
                  type="tree"
                  placeholder="请选择所属部门"
                />
              </template>
              <template slot="roleForm">
                <avue-select
                  v-model="role"
                  :dic="rolesOptions"
                  :props="roleProps"
                  multiple
                  placeholder="请选择角色"
                />
              </template>
            </avue-crud>
          </el-col>
        </el-row>
      </basic-container> -->
    <!-- </el-scrollbar> -->
  </div>
</template>

<script>
import { addObj, delObj, fetchList, putObj } from '@/api/admin/user'
import { deptRoleList } from '@/api/admin/role'
import { fetchTree } from '@/api/admin/dept'
import { tableOption } from '@/const/crud/admin/user'
import { mapGetters } from 'vuex'

export default {
  name: 'AuthorUser',
  data() {
    return {
      searchForm: {},
      // treeOption: {
      //   nodeKey: 'id',
      //   addBtn: false,
      //   menu: false,
      //   props: {
      //     label: 'name',
      //     value: 'id'
      //   }
      // },
      treeOption: {
        nodeKey: 'id',
        label: 'name',
        value: 'id'
      },
      treeData: [],
      option: tableOption,
      treeDeptData: [],
      checkedKeys: [],
      roleProps: {
        label: 'roleName',
        value: 'roleId'
      },
      defaultProps: {
        label: 'name',
        value: 'id'
      },
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条,
        isAsc: false// 是否倒序
      },
      list: [],
      listLoading: true,
      role: [],
      form: {},
      rolesOptions: [],
      filterText: '',
      defaultExpandedKeys: []
    }
  },
  computed: {
    ...mapGetters(['permissions'])
  },
  watch: {
    role() {
      this.form.role = this.role
    },
    list() {
      this.$nextTick(() => {
        this.$refs.elScrollbar.update()
      })
    },
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.sys_user_add = this.permissions.sys_user_add
    this.sys_user_edit = this.permissions.sys_user_edit
    this.sys_user_del = this.permissions.sys_user_del
    this.init()
  },
  methods: {
    // 树发生变化滚动条变化
    toggleChange() {
      this.$refs.treeScrollbar.update()
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    init() {
      fetchTree().then(response => {
        this.treeData = response.data.data

        if (this.treeData && this.treeData.length > 0) {
          this.defaultExpandedKeys.push(this.treeData[0].id)
        }
      })
    },
    nodeClick(data) {
      console.log(data)
      this.page.page = 1
      this.getList(this.page, { deptId: data.id })
    },
    getList(page, params) {
      this.listLoading = true
      fetchList(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, params, this.searchForm)).then(response => {
        this.list = response.data.data.records
        this.page.total = response.data.data.total
        this.listLoading = false
      })
    },
    getNodeData() {
      deptRoleList().then(response => {
        this.rolesOptions = response.data.data
      })
    },
    handleDept() {
      fetchTree().then(response => {
        this.treeDeptData = response.data.data
      })
    },
    handleFilter(param, done) {
      done()
      this.searchForm = param
      this.getList(this.page, param)
    },
    handleRefreshChange() {
      this.getList(this.page)
    },
    handleCreate() {
      this.$refs.crud.rowAdd()
    },
    handleOpenBefore(show, type) {
      window.boxType = type
      this.handleDept()
      if (['edit', 'views'].includes(type)) {
        this.role = []
        for (var i = 0; i < this.form.roleList.length; i++) {
          this.role[i] = this.form.roleList[i].roleId
        }
        deptRoleList().then(response => {
          this.rolesOptions = response.data.data
        })
      } else if (type === 'add') {
        this.role = []
      }
      show()
    },
    handleUpdate(row, index) {
      this.$refs.crud.rowEdit(row, index)
      this.form.password = undefined
    },
    create(row, done, loading) {
      if (this.form.phone.indexOf('*') > 0) {
        this.form.phone = undefined
      }
      addObj(this.form).then(() => {
        this.getList(this.page)
        done()
        this.$notify({
          title: '成功',
          message: '创建成功',
          type: 'success',
          duration: 2000
        })
      })['catch'](() => {
        loading()
      })
    },
    update(row, index, done, loading) {
      if (this.form.phone && this.form.phone.indexOf('*') > 0) {
        this.form.phone = undefined
      }
      putObj(this.form).then(() => {
        this.getList(this.page)
        done()
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
      })['catch'](() => {
        loading()
      })
    },
    deletes(row, index) {
      this.$confirm(
        '此操作将永久删除该用户(用户名:' + row.username + '), 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        delObj(row.userId)
          .then(() => {
            this.list.splice(index, 1)
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
          .cache(() => {
            this.$notify({
              title: '失败',
              message: '删除失败',
              type: 'error',
              duration: 2000
            })
          })
      })
    }
  }
}
</script>
<style lang="less">
.user {
  height: 100%;
  background-color:#fff;
  .treeWrapper{
    height:calc(100% - 40px)
  }
  &__tree {
    padding:10px;
    // padding-top: 3px;
    // padding-right: 20px;
    // padding-left: 20px;
  }

  &__main {
    .el-card__body {
      padding-top: 0;
    }
  }
}
</style>

